#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use FindBin;
use lib ("/net/cpp-group/Leo/bin", "$FindBin::Bin/..");

use linewrap;
#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888
my $usage = <<"USAGE";

USAGE:

    msf_to_fasta.pl sequences.msf [--help]
		
		This script accepts sequences in the msf format either in
		STDIN or on the command line and produces sequences reformatted
		in FASTA on STDOUT

USAGE
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory


# optional parameters
my $help = undef;
GetOptions('help' => \$help);

die $usage if ($help);

my $line_cnt = 0;

$_ = <>;
die "Error!\n\tMSF files start with the words 'PileUp'\n" unless /PileUp/;

my ($seq_len, $seq_type);
while (<>)
{
	if (/MSF:\s*(\d+)\s*Type:\s*([A-Z])/)
	{
		$seq_len = $1;													 	
		print STDERR "Warning:\n\tFile type = $2" unless $2 eq 'P';	
		last;
	}
}
die "Error!\n\tMSF files should contain a line like \n\t[MSF:  163  Type: P    Check:   871   ..]\n"
			unless defined ($seq_len);




my $fail = 1;
my @seq_names;
while (<>)
{
	if (/\/\//)
	{
		$fail = 0;
		last;
	}
	next unless /Name:\s*(.*?)\s*Len:/;
	push(@seq_names, $1);
}

my $curr_pos = 0;
my @seq_names_indices;
my $cnt_sequences = @seq_names;
# so can wrap around
push(@seq_names_indices, (0 .. ($cnt_sequences - 1)));	
push(@seq_names_indices, (0 .. ($cnt_sequences - 1)));
my %sequences;
while (<>)
{
	chomp;
	next unless length $_;
	for (my $i = $curr_pos; $i < $curr_pos + $cnt_sequences; ++$i)
	{
		my $index = $seq_names_indices[$i];
		if (/($seq_names[$index])\s+(.*)/)
		{
			$_ = $2;
			tr/[A-Z]\-\.//dc;
			tr/\./-/;
			$sequences{$seq_names[$index]} .= $_;
			$curr_pos = ($index + 1) % $cnt_sequences;
		}
	}
}

for (keys %sequences)
{
	print ">$_\n". linewrap($sequences{$_}, 60);
}
